
import React, { useState, useEffect, useContext, createContext } from 'react';
import Modal from 'react-bootstrap/Modal';
import Card from 'react-bootstrap/Card';
import Highlight from 'react-highlight';
import { Circles ,Rings, Hearts, SpinningCircles,TailSpin  } from 'svg-loaders-react';
import "highlight.js/styles/a11y-light.css";
import "./DialogLarge.css"
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faAngleRight } from '@fortawesome/free-solid-svg-icons';
import { faAngleDown } from '@fortawesome/free-solid-svg-icons';

import dayjs from 'dayjs';
import { Table, Form, Button } from 'react-bootstrap';

//props.isOpen
//props.lyrParams
//props.onOk
//props.onCancel
//props.onSelectROIClick
//props.selectedROI
//props.appCurrentROI
//props.appDateA
//props.appDateB 
//props.loginedUser
//props.openlayerRef 
//
function DialogLargeOmc(props) {

    const [pdtName, setPdtName] = useState("");
    const [roiObject, setRoiObject] = useState(null);
    const [extentTemChecked, setExtentTemChecked] = useState(false);
    const [extentRoiChecked, setExtentRoiChecked] = useState(false);
    const [extentViewChecked, setExtentViewChecked] = useState(true);
    const [temList, setTemList] = useState([]);
    const [selectedTemIndex, setSelectedTemIndex] = useState(-1);
    const [isBusy, setIsBusy] = useState(false);

    useEffect(() => {
        setIsBusy(false);
        if (props.lyrParams !== null) {
            if (typeof props.lyrParams.productDisplay !== 'undefined') {
                setPdtName(props.lyrParams.productDisplay.productname);
            } else {
                setPdtName(props.lyrParams.name);
            }
        } else {
            setPdtName("");
        }
        httpGetTemList();
    }, [props.lyrParams]);

    useEffect(() => {
        if (props.selectedROI !== null) {
            setRoiObject(props.selectedROI);
        }
    }, [props.selectedROI]);



    const httpGetTemList = function () {
        let dpid1 = 0;
        if(  props.lyrParams!==null && typeof props.lyrParams.productDisplay !== 'undefined') {
            dpid1 = props.lyrParams.productDisplay.dpid;
        }
        let url1 = global.g_serverAPIRoot 
            + "omc/temlist3?uid="+props.loginedUser.uid+"&dpid="+dpid1;
        fetch(url1)
            .then((response) => response.json())
            .then((result) => {
                if (result.state === 0) {
                    setTemList(result.data);
                } else {

                }
            }).catch(err => {
                window.alert(err);
            })
    };


    const onCurrentROIClick = function () {
        setRoiObject(props.appCurrentROI);
    }

    const onClearROIClick = function () {
        setRoiObject(null);
    }

    const onCheckChange1 = function (ev) {
        let c1 = !extentTemChecked;
        if (c1 === true) {
            setExtentTemChecked(true);
            setExtentRoiChecked(false);
            setExtentViewChecked(false);
        }
    }
    const onCheckChange2 = function (ev) {
        let c1 = !extentRoiChecked;
        if (c1 === true) {
            setExtentTemChecked(false);
            setExtentRoiChecked(true);
            setExtentViewChecked(false);
        }
    }
    const onCheckChange3 = function (ev) {
        let c1 = !extentViewChecked;
        if (c1 === true) {
            setExtentTemChecked(false);
            setExtentRoiChecked(false);
            setExtentViewChecked(true);
        }
    }

    //js Date 对象转Long型 YYYYMMDD000000 数据，注意目前时分秒使用0代替。
    const convertJsDate2Ymd14 = function (jsDate) {
        const dayjsdate = dayjs(jsDate);
        const datetime1 = dayjsdate.format("YYYYMMDD000000");
        return datetime1;
    }

    //上传geojson到用户roi表中，结果返回上传后的roi对象
    const httpUploadGeojson = async function (uid, name, geojsonstr) {
        const url1 = global.g_serverAPIRoot + "roi/newgeojson";
        const formData = new FormData();
        formData.append('uid', uid);
        formData.append('name', name);
        formData.append('geojson', geojsonstr);
        const response = await fetch(url1, { method: 'POST', body: formData, });
        const result = await response.json();
        if (result.state === 0) {
            return result.data;
        } else {
            alert(result.message);
            return null;
        }
        return null;
    }


    const onOk = async function () {
        //必须有模板选中
        if (selectedTemIndex === -1 || selectedTemIndex >= temList.length) return;

        const templateObj1 = temList[selectedTemIndex];
        let datetime1 = 0;
        if (props.lyrParams.front_group === 'A') {
            datetime1 = convertJsDate2Ymd14(props.appDateA);
        } else {
            datetime1 = convertJsDate2Ymd14(props.appDateB);
        }

        let pid = 0;
        let sid = 0;
        if (props.lyrParams.productDisplay.type === 'pe' || props.lyrParams.productDisplay.type === 'ud') {
            pid = props.lyrParams.pid;
        } else if (
            props.lyrParams.productDisplay.type === 'pes' || props.lyrParams.productDisplay.type === 'us'
        ) {
            const tempObj = JSON.parse(props.lyrParams.productDisplay.params);
            sid = tempObj.sid;
        } else {
            // xyz wms pgm do nothing
            window.alert("not supported product type:" + props.lyrParams.productDisplay.type);
            return;
        }
        const styleid1 = props.lyrParams.styleid;
        let sduistr1 = 'null';
        if (typeof props.lyrParams.sdui !== 'undefined' && props.lyrParams.sdui !== null) {
            let slimSdui = {};
            for (let key in props.lyrParams.sdui) {
                slimSdui[key] = { val: props.lyrParams.sdui[key].val };
            }
            sduistr1 = JSON.stringify(slimSdui);
        }
        let uid1 = props.loginedUser.uid;


        setIsBusy(true);
        let roiid = "null";
        if (roiObject !== null) {
            if (roiObject.rid !== 0) {
                roiid = "sys:" + roiObject.rid;
                if (roiObject.uid > 0) roiid = "user:" + roiObject.rid;
            } else {
                const tempRoiObject = await httpUploadGeojson(uid1, roiObject.name, roiObject.geojson);
                if (tempRoiObject === null) {
                    setIsBusy(false);
                    return;
                }
                setRoiObject(tempRoiObject);
                roiid = "user:" + tempRoiObject.rid;
            }
        }

        const formData = new FormData();
        formData.append('uid', uid1);
        formData.append('datetime', datetime1);
        formData.append('styleid', styleid1);
        formData.append('sdui', sduistr1);
        formData.append('pid', pid);
        formData.append('sid', sid);
        formData.append('roiid', roiid);
        formData.append("temfile", templateObj1.file);
        let zoomtype = 'tem';//0-use template, 1-use roi, 2-use view.
        if (extentRoiChecked === true) zoomtype = 'roi';
        if (extentViewChecked === true) zoomtype = 'view';
        const olextent = props.openlayerRef.current.getMapExtent();
        let x0 = Math.max(-180, olextent[0]);
        let y0 = Math.max(-90, olextent[1]);
        let x1 = Math.min(180, olextent[2]);
        let y1 = Math.min(90, olextent[3]);
        formData.append("left", x0);
        formData.append("right", x1);
        formData.append("top", y1);
        formData.append("bottom", y0);


        formData.append("zoomtype", zoomtype);
        let url1 = global.g_serverAPIRoot + "omc/newfromtem2";
        fetch(url1, { method: 'POST', body: formData, })
            .then((response) => response.json())
            .then((result) => {
                console.log("debug 1 post new from tem2 ");
                console.log(result);

                if (result.state === 0) {
                    setIsBusy(false);
                    const olextent = props.openlayerRef.current.getMapExtent() ;
                    let x0 = Math.max(-180, olextent[0]) ;
                    let y0 = Math.max(-90, olextent[1]) ;
                    let x1 = Math.min(180, olextent[2]) ;
                    let y1 = Math.min(90, olextent[3]) ;
                    const url1 = global.g_omcindexpageurl+"?file="+result.data
                    +"&x0="+x0.toFixed(5)+"&y0="+y0.toFixed(5)
                    +"&x1="+x1.toFixed(5)+"&y1="+y1.toFixed(5) 
                    + "&uid=" + uid1 ;
                    window.open(url1, "_blank") ;

                    props.onOk();
                    setExtentTemChecked(false);
                    setExtentRoiChecked(false);
                    setExtentViewChecked(true);
                    setSelectedTemIndex(-1);

                } else {
                    //bad
                    setIsBusy(false);
                    alert(result.message);
                }
            }).catch(err => {
                setIsBusy(false);
                alert(err);
            })
            ;
    }

    const onCancel = function () {
        props.onCancel();
        setExtentTemChecked(false);
        setExtentRoiChecked(false);
        setExtentViewChecked(true);
        setRoiObject(null);
        setSelectedTemIndex(-1);
    }


    return (
        <Modal
            show={props.isOpen}
            dialogClassName="DialogLarge"
        >
            <Modal.Body className='DialogLargeModelBody' >
                <div style={{ width: '100%', height: '100%', padding: '6px' }}>
                    {/* header and title */}
                    <div style={{ width: '100%', backgroundColor: '#3597D1', height: '30px', padding: '7px', color: 'white', fontSize: '16px' }}>
                        <span style={{ borderLeftWidth: '4px', borderLeftColor: 'white', borderLeftStyle: 'solid', marginRight: '8px' }}></span>
                        {pdtName}专题图生成
                    </div>

                    {/* body */}
                    <div style={{ backgroundColor: 'white', height: '800px', padding: '8px' }}>
                        <div>请选择模板:</div>
                        {/* 模板列表 */}
                        <div style={{ backgroundColor: '#EEE', height: '600px', overflowY: 'auto', boxShadow: 'rgb(71 160 210 / 30%) 0px 2px 2px 0px' }}>
                            {
                                temList.map((item, index) => (
                                    <Card
                                        className={(index === selectedTemIndex) ? 'SelectedTemCardBorder' : ''}
                                        key={index}
                                        bg='light'
                                        style={{ margin: '4px', width: '17.4rem', float: 'left' }}
                                        onClick={() => setSelectedTemIndex(index)}
                                    >
                                        <Card.Img variant="top" src={global.g_staticResourceRoot + item.file + '.thumb.png'} />
                                        <Card.Body>
                                            {item.name}
                                        </Card.Body>
                                    </Card>

                                )
                                )
                            }
                        </div>

                        {/* 感兴趣区 */}
                        <div style={{ margin: '8px' }}>
                            <div style={{ float: 'left' }}>感兴趣区:</div>
                            <Form.Control placeholder='请选择感兴趣区' type="text"
                                style={{ width: '240px', float: 'left' }} disabled size='sm'
                                value={(roiObject !== null) ? roiObject.name : ""}
                            />
                            <Button size='sm' variant="success"
                                style={{ marginLeft: '8px' }}
                                onClick={onCurrentROIClick}>当前ROI</Button>
                            <Button size='sm' variant="secondary"
                                style={{ marginLeft: '8px' }}
                                onClick={props.onSelectROIClick}>选择ROI</Button>
                            <Button size='sm' variant="warning"
                                style={{ marginLeft: '8px' }}
                                onClick={onClearROIClick}>清除ROI</Button>
                            <div style={{ clear: 'both' }}></div>
                        </div>

                        {/* 缩放 */}
                        <div style={{ margin: '8px' }}>
                            <div style={{ float: 'left' }}>主地图范围:</div>
                            <Form>
                                <Form.Check
                                    type='radio'
                                    label="模板范围"
                                    name="group_mapextent"
                                    id='zoomExtent_tem'
                                    style={{ marginLeft: '8px', width: '140px', float: 'left' }}
                                    checked={extentTemChecked}
                                    onChange={onCheckChange1}
                                />
                                <Form.Check
                                    type='radio'
                                    label="感兴趣区范围"
                                    id='zoomExtent_roi'
                                    name="group_mapextent"
                                    style={{ width: '140px', float: 'left' }}
                                    checked={extentRoiChecked}
                                    onChange={onCheckChange2}
                                />
                                <Form.Check
                                    type='radio'
                                    label="当前视图范围"
                                    id='zoomExtent_map'
                                    name="group_mapextent"
                                    style={{ width: '140px', float: 'left' }}
                                    checked={extentViewChecked}
                                    onChange={onCheckChange3}
                                />
                            </Form>


                            <div style={{ clear: 'both' }}></div>
                        </div>
                    </div>

                    {/* footer */}
                    <div style={{ padding: '4px', height: '38px', backgroundColor: 'white', boxShadow: '0px -2px 2px 0px rgba(71,160,210,0.3)' }}>
                        <Button
                            className='rsbig-button'
                            style={{ float: 'left' }}
                            variant="secondary" size="sm"
                        >帮助</Button>
                        <Button
                            className='rsbig-button'
                            style={{ float: 'right' }}
                            variant="secondary" size="sm"
                            onClick={onCancel} >取消</Button>

                        {
                            (isBusy === true) ? <Circles strokeWidth="4px" fill="rgb(53, 151, 209)" stroke="rgb(53, 151, 209)" style={{ float: 'right',height:'30px' }} /> :
                                (
                                    <Button
                                        className='rsbig-button'
                                        style={{ backgroundColor: 'rgb(53, 151, 209)', float: 'right', marginRight: '10px' }}
                                        variant="primary" size="sm"
                                        onClick={onOk}>确定</Button>
                                )
                        }

                        <div style={{ clear: 'both' }}></div>
                    </div>
                </div>
            </Modal.Body>
        </Modal>
    )
}

export default DialogLargeOmc